﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SmartApi.Utils
{
    public class QueryStringParser
    {
        public string Parse(IDictionary<string, RequestParameter> parameters)
        {
            StringBuilder queryStringBuilder = new StringBuilder();
            foreach (var reqParam in parameters)
            {
                var paramName = reqParam.Key;
                var paramVal = reqParam.Value;
                var realVal = paramVal?.Value;
                if (paramVal.Position != Annotations.PatameterPosition.Query) { continue; }

                if (realVal == null) { queryStringBuilder.AppendFormat("&{0}={1}", reqParam.Key, ""); }
                if (realVal.GetType().IsClass)
                {
                    var childDic = realVal.ToDictionary();
                    foreach (var childReqParam in childDic)
                    {
                        queryStringBuilder.AppendFormat("&{0}={1}", childReqParam.Key, childReqParam.Value);
                    }
                }
                else
                {
                    queryStringBuilder.AppendFormat("&{0}={1}", reqParam.Key, reqParam.Value);
                }
            }
            var queryString = queryStringBuilder.ToString();
            if (queryString.Length > 0)
            {
                queryString = queryString.Substring(1);
            }
            return queryString;
        }
    }
}
